package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.fragment.DonationRecordFragment;
import com.srwl.mytx.fragment.DonationRecordFragment_v1;
import com.srwl.mytx.fragment.TopicFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.DateUtil;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoonUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserProfileActivity extends BaseActivity {

    public static void startActivity(Context context, User user) {
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(Constant.EXTRA_TARGET_USER_INFO, user));
    }

    private static final String TAG = "UserProfileActivity";
    private static final int REQUESTCODE_PICK = 1;
    private static final int REQUESTCODE_CUTTING = 2;
    private static final int QUERY_MY_CAR_SUCCESS = 0;
    // Toolbar toolbar;
    private TabLayout tab_bar;
    private ImageView avatar;
    private Button btn_sendMessage;
    private Context context;
    private List<Topic> topicList;
    private View parent;
    private User targetUser;
    private TextView tv_gender;
    private Button btn_follow;
    private ViewPager vp_container;
    private TextView tv_donationAmount;
    private View rl_userInfoContainer;
    private AppBarLayout appBarLayout;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private TextView tv_title;
    private Toolbar toolbar;
    private ProgressBar progressBar;
    private int totalScrollHeight;
    private int titleWidth;
    private int titleHeight;
    private float originalTitleX;
    private float originalTitleY;
    private int titleBarWidth;//标题栏的宽度就是屏幕宽度，
    private int titleBarHeight;//布局文件中设置的是50dp
    private float titleBarTop;
    private FrameLayout.LayoutParams params;
    private float totalScrollX;
    private float totalScrollY;
    private String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
    private TextView tv_follow_num;
    private TextView tv_fans_num;
    private boolean isAttention;
    private TopicFragment topicFragment;
    private boolean syncUserInfo;
    private Long fansNum;
    private Long attentionSize;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_user_profile);

        context = this;
        topicList = new ArrayList<>();
        targetUser = getIntent().getParcelableExtra(EaseConstant.EXTRA_TARGET_USER_INFO);
        syncUserInfo = getIntent().getBooleanExtra(Constant.SYNC_USER_INFO, true);
        initView();
        initListener();
        initData();
    }

    private void initView() {
        tv_fans_num = findViewById(R.id.tv_fans_num);
        tv_follow_num = findViewById(R.id.tv_follow_num);
        toolbar = findViewById(R.id.toolbar);
        tab_bar = findViewById(R.id.tab_bar);
        avatar = findViewById(R.id.iv_icon);
        tv_gender = findViewById(R.id.tv_gender);
        TextView tv_area = findViewById(R.id.tv_area);
        btn_sendMessage = findViewById(R.id.btn_send_message);
        btn_follow = findViewById(R.id.btn_follow);
        rl_userInfoContainer = findViewById(R.id.rl_user_info_container);
        tv_title = findViewById(R.id.tv_title);
        tv_donationAmount = findViewById(R.id.tv_donation_amount);
        collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar_layout);
        progressBar = findViewById(R.id.progress_bar);
        findViewById(R.id.ll_fans).setOnClickListener(v -> showFansRecord());
        findViewById(R.id.ll_follow).setOnClickListener(v -> showFollowRecord());
        // collapsingToolbarLayout.setContentScrimColor(Color.TRANSPARENT);
        // collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
//        collapsingToolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.text_black));
//        collapsingToolbarLayout.setExpandedTitleMarginStart(Utils.dpToPx(80, this));
//        collapsingToolbarLayout.setExpandedTitleMarginTop(Utils.dpToPx(80, this));
        //collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        // collapsingToolbarLayout.setContentScrimColor(Color.WHITE);
        appBarLayout = findViewById(R.id.app_bar);
        //  totalScrollHeight = Utils.dpToPx(150 - 50, this);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (titleHeight == 0) {
                    totalScrollHeight = appBarLayout.getTotalScrollRange();
                    titleWidth = tv_title.getWidth();
                    titleHeight = tv_title.getHeight();
                    Log.d(TAG, "titleHeight: " + titleHeight);
                    originalTitleX = tv_title.getX();
                    originalTitleY = tv_title.getY();
                    Log.d(TAG, "originalTitleY: " + originalTitleY);
                    titleBarWidth = toolbar.getWidth();
                    titleBarHeight = toolbar.getHeight();
                    Log.d(TAG, "titleBarHeight: " + titleBarHeight);
                    titleBarTop = toolbar.getTop();
                    Log.d(TAG, "titleBarTop: " + titleBarTop);
                    totalScrollX = (titleBarWidth - titleWidth) / 2 - originalTitleX;
                    //tv_title 最后的 y 坐标减去原始的Y坐标，等于变化的Y坐标值，根据滑动距离的百分比，最后计算出 Y 方向上的位移
                    totalScrollY = (toolbar.getPaddingTop() + toolbar.getHeight()) / 2 - (titleHeight) / 2 - originalTitleY;
                    Log.d(TAG, "totalScrollY: " + totalScrollY);
                    //  params = (FrameLayout.LayoutParams) tv_title.getLayoutParams();

                }

                // double rate = (-verticalOffset) / totalScrollHeight;
                float rate = new BigDecimal((float) (-verticalOffset) / totalScrollHeight).setScale(2, BigDecimal.ROUND_FLOOR).floatValue();

                rl_userInfoContainer.setAlpha(1 - (rate > 1 ? 1 : rate));

                //params.leftMargin = (int) (originalTitleX + totalScrollX * (rate > 1 ? 1 : rate));
                // params.topMargin = (int) (originalTitleY - totalScrollY * (rate > 1 ? 1 : rate));

                // tv_title ，放CollapsingToolbarLayout里面，通过设置 LayoutParams，可以实现 自定义标题 居中显示，但是 logcat 一直报警告，requestLayout.....
                // tv_title.requestLayout();
                // tv_title.setLayoutParams(params);
                //tv_title 放CoordinatorLayout 里面，通过设置位移，也可以实现 自定义标题居中显示，但是 字体颜色最后会变成灰色，就在TabLayout滑动到极限，出现下边缘阴影的时候，字体就变灰色了
                tv_title.setTranslationX(totalScrollX * (rate > 1 ? 1 : rate));
                tv_title.setTranslationY(totalScrollY * (rate > 1 ? 1 : rate));//也可以设置滑动因子0.7 ，看起也是基于toolbar 垂直居中的
                tv_title.setScaleX(1 - 0.3f * (rate > 1 ? 1 : rate));
                tv_title.setScaleY(1 - 0.3f * (rate > 1 ? 1 : rate));
                // Log.d(TAG, "onOffsetChanged: " + (totalScrollY * (rate > 1 ? 1 : rate)));
            }
        });


        initViewPage();

        if (targetUser != null) {
            //  collapsingToolbarLayout.setTitle(targetUser.getUsername());
            if (targetUser.getUsername() != null) {
                tv_title.setText(targetUser.getUsername());
            } else {
                tv_title.setText(targetUser.getNick());
            }
            tv_area.setText(targetUser.getArea());
            if (targetUser.getGender() != null) {
                if (targetUser.getGender().equals(1)) {
                    tv_gender.setText("女");
                } else if (targetUser.getGender().equals(0)) {
                    tv_gender.setText("男");
                }
            } else {
                tv_gender.setVisibility(View.GONE);
            }

            GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), avatar, R.drawable.tx_default_avatar_1);
            //没绑手机号隐藏关注 (注释，没绑定手机号，能被人打开 用户主页，应该就是 授权登录用户，应该可以接受关注)
//            if (TextUtils.isEmpty(targetUser.getPhone())) {
//                btn_follow.setEnabled(false);
//            }
            //如果是自己打开了自己的用户详情页面，就禁用 关注和聊天的按键
            if (loginUserId.equals(targetUser.getuId()) || Utils.isTempUser(targetUser)) {
                // btn_follow.setEnabled(false);
                // btn_sendMessage.setEnabled(false);
                btn_follow.setVisibility(View.GONE);
                btn_sendMessage.setVisibility(View.GONE);
            }

            //如果目标用户就是当前登录用户，并且当前用户是“游客”，就不查询数据
            if (targetUser.getType() != null && TextUtils.equals(targetUser.getuId(), UserProfileManager.getInstance().getUserID()) && Constant.USER_TYPE_TEMP == targetUser.getType()) {
                tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, "0"));
                tv_follow_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, "0"));
            } else if (syncUserInfo) {
                fetchUserInfo(targetUser.getuId());
            } else if (targetUser.getFans() == null || targetUser.getAttentionSize() == null) {
                checkFollow();
                // tv_donationAmount.setText(Utils.moneyFormat(targetUser.getDonationAmount()));
            } else {
                fansNum = targetUser.getFans();
                attentionSize = targetUser.getAttentionSize();
                String fansString = Utils.numberFormat(targetUser.getFans());
                tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, fansString));
                String attentionString = Utils.numberFormat(targetUser.getAttentionSize());
                tv_follow_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, attentionString));
                isAttention = targetUser.isAttention();
                if (isAttention) {
                    btn_follow.setText("已关注");
                }
            }
            String donationString = Utils.moneyFormat(targetUser.getDonationAmount());
            tv_donationAmount.setText(MoonUtils.getSpannableString_red(UserProfileActivity.this, donationString));
        }
    }

    private void showFollowRecord() {
        startActivity(new Intent(this, FollowFansRecordActivity.class).putExtra("uid", targetUser.getuId()));
    }

    private void showFansRecord() {
        startActivity(new Intent(this, FollowFansRecordActivity.class).putExtra(Constant.EXTRA_INFO_IS_SHOW_FANS, true).putExtra("uid", targetUser.getuId()));
    }

    private void initViewPage() {
        vp_container = findViewById(R.id.vp_container);
        vp_container.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_bar));
        tab_bar.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(vp_container));
        final DonationRecordFragment_v1 donationRecordFragment = DonationRecordFragment_v1.newInstance(targetUser.getuId());
        donationRecordFragment.setListener(isShowProgressBar -> {

            if (isShowProgressBar && !progressBar.isShown()) {
                progressBar.setVisibility(View.VISIBLE);
            } else if (!isShowProgressBar && progressBar.isShown()) {
                progressBar.setVisibility(View.GONE);
            }
        });
        topicFragment = TopicFragment.newInstance(2, targetUser.getuId());
        vp_container.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return donationRecordFragment;
                    case 1:
                        return topicFragment;

                    default:
                        return null;
                }
            }

            @Override
            public int getCount() {
                return 2;
            }
        });
    }


    private void initData() {
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

    }


    private void initListener() {
        btn_follow.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isFastClick()) return;

                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    LoginActivity.startActivity(UserProfileActivity.this, "关注他需要先登录");
                    return;
                }

                if (isAttention) {
                    removeFollow(targetUser.getuId());

                } else {
                    follow(targetUser.getuId());

                }
                setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_TARGET_USER, targetUser));
            }
        });
        toolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                back(view);
            }
        });
        btn_sendMessage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UserProfileActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
    }


    public void fetchUserInfo(final String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }

        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo_v1(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, body.getMsg());

                            if (body.getStatus() == Constant.USER_NAME_INVALID) {
                                showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) body.getData();
                        Log.i(TAG, "onResponse: " + jsonObject.toJSONString());
                        User user = jsonObject.toJavaObject(User.class);
                        fansNum = user.getFans();
                        attentionSize = user.getAttentionSize();
                        String donationString = Utils.moneyFormat(user.getDonationAmount());
                        tv_donationAmount.setText(MoonUtils.getSpannableString_red(UserProfileActivity.this, donationString));
                        String fansString = Utils.numberFormat(user.getFans());
                        tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, fansString));
                        String attentionString = Utils.numberFormat(user.getAttentionSize());
                        tv_follow_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, attentionString));
                        isAttention = user.isAttention();
                        if (isAttention) {
                            btn_follow.setText("已关注");
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        UserProfileActivity.this.showToast_v1(getString(R.string.system_busy));
                    }
                });

    }

    /**
     * 查询关注粉丝数量
     *
     * @param
     */
    private void checkFollow() {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        String targetUid = targetUser.getuId();
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);
        //如果目标用户就是当前登录用户，并且当前用户是“游客”
        if (targetUser.getType() != null && TextUtils.equals(targetUid, UserProfileManager.getInstance().getUserID()) && Constant.USER_TYPE_TEMP == targetUser.getType()) {
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .checkAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: " + response.message());
//                    ConfirmDialog dialog = new ConfirmDialog(context, "提示", "系统繁忙");
//                    dialog.show();
                    return;
                }
                JSONObject data = (JSONObject) response.body().getData();

                fansNum = data.getLong("fansNum");
                attentionSize = data.getLong("attentionSize");
                isAttention = data.getBoolean("attentionSize");
                String fansString = Utils.numberFormat(fansNum);
                tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, fansString));
                String attentionString = Utils.numberFormat(attentionSize);
                tv_follow_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, attentionString));
                if (isAttention) {
                    btn_follow.setText("已关注");
                }


            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
            }
        });


    }

    /**
     * 关注
     *
     * @param targetUid
     */
    private void follow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        btn_follow.setEnabled(false);
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .addAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                btn_follow.setEnabled(true);
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: " + response.message());
                    return;
                }
                if (result.isError()) {

                    Log.e(TAG, "onResponse: " + result.getMsg());
                    return;
                }
                btn_follow.setText("已关注");
                isAttention = true;
                targetUser.setAttention(true);
                fansNum++;
                tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, Utils.numberFormat(fansNum)));
            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                btn_follow.setEnabled(true);
                Log.e(TAG, "onFailure: " + t.getMessage());
                ConfirmDialog dialog = new ConfirmDialog(context, "提示", "关注失败");
                dialog.show();

            }
        });
    }


    /**
     * 取消关注
     *
     * @param
     */
    private void removeFollow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        btn_follow.setEnabled(false);
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .removeAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                btn_follow.setEnabled(true);
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: " + response.message());

                    return;
                }
                if (result.isError()) {
                    Log.e(TAG, "onResponse: " + result.getMsg());
                    return;
                }
                btn_follow.setText("关注");
                isAttention = false;
                targetUser.setAttention(false);
                fansNum--;
                tv_fans_num.setText(MoonUtils.getSpannableString(UserProfileActivity.this, Utils.numberFormat(fansNum)));
            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                btn_follow.setEnabled(true);
                Log.e(TAG, "onFailure: " + t.getMessage());
                ConfirmDialog dialog = new ConfirmDialog(context, "提示", "取消关注失败");
                dialog.show();

            }
        });
    }


    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onAccountChange() {
        super.onAccountChange();
        onCreate(null);
    }
}
